#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import calendar
import optparse
import os.path
import shutil
import subprocess
import sys
import tempfile
import time

if __name__=="__main__":
    try:
        videoFile = sys.argv[1]
    except:
        print("Gimme a video file to work on!", file=sys.stderr)
        sys.exit(2)

    # FIgure out video length.
    errorCode, output = subprocess.getstatusoutput('ffmpeg -i "%s"'%videoFile)
    videoLength = 0
    videoStream = ""
    audioStream = ""
    summaryLine = ""
    for line in output.split('\n'):
        line = line.strip()
        if line.startswith("Duration:"):
            summaryLine = line
            line = line.replace("Duration:", "1970-01-01").split('.')[0]
            structTime = time.strptime(line, "%Y-%m-%d %H:%M:%S")
            videoLength = calendar.timegm(structTime)
        if line.startswith("Stream #"):
            if line.find("Video")>-1:
                videoStream = line
            elif line.find("Audio")>-1:
                audioStream = line

    # Create a temporary folder.
    tmpDir = tempfile.mkdtemp()
    # Calculate how many images are required.
    # Also make sure that the imageCount is divisible by three.
    imageCount = int(videoLength/60)
    imageCount += (3-imageCount%3)
    # #   # # imageCount = 30
    # Get a range to loop over.
    percentages = range(0,100,int(100/imageCount))
    for pct in percentages:
        # Bypass the zero image, it's usually a black frame.
        if pct:
            timeStamp = time.strftime("%H_%M_%S", time.gmtime(videoLength*pct/100))
            clock = timeStamp.replace("_", ":")
            outputFile = "%s/%s.png"%(tmpDir, timeStamp)
            captionedOutput = "%s/caption_%s.png"%(tmpDir, timeStamp)
            errorCode, output = subprocess.getstatusoutput('ffmpegthumbnailer -s 320 -t %d%% -o "%s" -i "%s"'%(pct, outputFile, videoFile))
            print("Working... %3d%%"%pct, end='\r')
            # Get image size.
            errorCode, output = subprocess.getstatusoutput('identify "%s"'%outputFile)
            geometry = output.split("PNG")[1].split()[0].split('x')
            imageWidth = int(geometry[0])
            imageHeight = int(geometry[1])
            # Annotate thumbnails with timestamps.
            command = """convert \
%s -fill '#0008' -draw 'rectangle 0,%d,%d,%d' \
-font Ubuntu-Regular -fill white \
-annotate +10+%d %s %s"""%(outputFile,
                        imageHeight-20,
                        imageWidth,
                        imageHeight,
                        imageHeight-5,
                        clock,
                        captionedOutput)
            errorCode, output = subprocess.getstatusoutput(command)
    print("Working... 100%\nGenerating montage...")
    # Generate montage.
    firstMontage = "%s/%s.png"%(tmpDir,
                                os.path.splitext(videoFile)[0])
    command = """montage \
-font Ubuntu-Regular -tile 3 -geometry +1+1 \
%s/caption_*.png %s"""%(tmpDir, firstMontage)
    errorCode, output = subprocess.getstatusoutput(command)
    # Annotate montage.
    print("Annotating montage...")
    command = """convert %s -background white \
label:'%s\n%s\n%s\n%s' \
+swap -font Ubuntu-Regular -pointsize 20 \
-append %s.png"""%(firstMontage,
                                        videoFile,
                                        summaryLine,
                                        videoStream,
                                        audioStream,
                                        os.path.splitext(videoFile)[0])
    errorCode, output = subprocess.getstatusoutput(command)
    print("Montage saved as '%s.png'."%os.path.splitext(videoFile)[0])
    # Remove temporary directory.
    print("Cleaning up...")
    shutil.rmtree(tmpDir)
    print("All done, TTFN.")
